package com.tcpengine.server;

import com.tcpengine.handler.GameProcess;
import com.tcpengine.handler.TcpHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TcpService implements Runnable {

	GameProcess m_gameProcess = null;
	public TcpService(GameProcess gameProcess) {
		m_gameProcess = gameProcess;
	}
	
	@Override
	public void run() {
		EventLoopGroup tcpBossGroup = new NioEventLoopGroup();
		EventLoopGroup tcpWorkerGroup =new NioEventLoopGroup();
		ChannelFuture tcpChannel  =null;
        try{
    		try{
    			ServerBootstrap bootstrap = new ServerBootstrap();
    			bootstrap.group(tcpBossGroup, tcpWorkerGroup).channel(NioServerSocketChannel.class)
    			.option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<SocketChannel>() {

    				@Override
    				protected void initChannel(SocketChannel arg0) throws Exception {
    					// arg0.pipeline().addLast(new MsgDecoder());	
    					// arg0.pipeline().addLast(new MsgEncoder());									
    					arg0.pipeline().addLast(new TcpHandler(m_gameProcess));
    				}
    			});
    			bootstrap.option(ChannelOption.TCP_NODELAY, true);
    			bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    			bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    			bootstrap.option(ChannelOption.SO_SNDBUF, 1024);
    			bootstrap.option(ChannelOption.SO_RCVBUF, 1024);			
    			
    			System.out.println("开启tcp协议端口: 8889");
    			tcpChannel = bootstrap.bind(8889);
    			tcpChannel.channel().closeFuture().sync();
    			
    		}catch (Exception e) {
    			e.printStackTrace();
    		}
        }finally {
            tcpBossGroup.shutdownGracefully();
            tcpWorkerGroup.shutdownGracefully();
            System.out.println("关闭tcp协议端口: 8889");
        }
	}
}
